package com.aglhz.nature.view;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.aglhz.base.BaseActivity;
import com.aglhz.nature.R;
import com.aglhz.nature.utils.Constants;
import com.aglhz.nature.utils.MD5;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class SecondHomeWebActivity extends BaseActivity {
	private SharedPreferences sharedPreferences;  
	private String token;
	private WebView re_webView;
	private String link;
	private String seclink;
	private String secondLink;
	private String wx_token;
	private String nor_token;
	private IWXAPI api;
	private String homeScrollView;
	private String homeSecLIST;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homereweb);
		setActionBarTitle("溯源商品列表");
		
		api = WXAPIFactory.createWXAPI(getApplication(), Constants.WX_KEY);
		re_webView=(WebView) findViewById(R.id.re_webView);
		Intent intent=getIntent();
		link = intent.getStringExtra("homeRE3");
		seclink= intent.getStringExtra("SecClassLink");
		secondLink= intent.getStringExtra("SearchRecommed");
		homeScrollView=intent.getStringExtra("HomeScrollView");
		homeSecLIST=intent.getStringExtra("HomeSecLIST");
		if(!TextUtils.isEmpty(link)){
			setActionBarTitle("商品详情");
		}else if(!TextUtils.isEmpty(seclink)){
			setActionBarTitle("商品详情");
		}else if(!TextUtils.isEmpty(homeScrollView)){
			setActionBarTitle("商品详情");
		}else if(!TextUtils.isEmpty(homeSecLIST)){
			setActionBarTitle("商品详情");
		}
		
		//获取sharedPreferences里面的信息,微信
		sharedPreferences =getSharedPreferences("WX_INFO", Context.MODE_PRIVATE);
		wx_token=sharedPreferences.getString("token", "");
		//获取sharedPreferences里面的信息,普通登陆
		sharedPreferences = getSharedPreferences("Normal_Info",Context.MODE_PRIVATE);
		nor_token=sharedPreferences.getString("NORMAL_Token", "");
		if(!(""==wx_token)){
			token=wx_token;
		}else{
			token=nor_token;
		}
		WebSettings webSettings = re_webView.getSettings();  
	    //设置WebView属性，能够执行Javascript脚本    
	    webSettings.setJavaScriptEnabled(true);    
	    //设置可以访问文件  
	    webSettings.setAllowFileAccess(true);  
	  //webview自适应屏幕
	    webSettings.setUseWideViewPort(true); 
	    webSettings.setLoadWithOverviewMode(true); 
	    if(!TextUtils.isEmpty(link)){
	    	re_webView.loadUrl(link+"&viewType=1&token="+token+"&appType=2");    
		    Log.e("url",link+"?token="+token+"&appType=2");
	    }else if(!TextUtils.isEmpty(seclink)){
	    	re_webView.loadUrl(seclink+"&viewType=1&token="+token+"&appType=2");    
		    Log.e("url",link+"?token="+token+"&appType=2");
	    }else if(!TextUtils.isEmpty(secondLink)){
	    	re_webView.loadUrl(secondLink+"&viewType=1&token="+token+"&appType=2");    
		    Log.e("secondLink",secondLink);
	    }else if(!TextUtils.isEmpty(homeScrollView)){
	    	re_webView.loadUrl(homeScrollView+"&viewType=1&token="+token+"&appType=2");    
		    Log.e("homeScrollView",homeScrollView);
	    }else if(!TextUtils.isEmpty(homeSecLIST)){
	    	re_webView.loadUrl(homeSecLIST+"&viewType=1&token="+token+"&appType=2");    
		    Log.e("homeSecLIST",homeSecLIST);
	    }
	  
	    //设置Web视图  
	    re_webView.setWebChromeClient(new WebChromeClient());
	    re_webView.setWebViewClient(new WebViewClient(){
	        @Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
	            view.loadUrl(url);
	            return true;
	        }	       
	        @Override
	        public void onPageStarted(WebView view, String url, Bitmap favicon) {	        	
	        	super.onPageStarted(view, url, favicon);	    	
	        }
	        
	        @Override
			public void onPageFinished(WebView view, String url) {				
				super.onPageFinished(view, url);			
			}
	    });
	    re_webView.addJavascriptInterface(new JavaScriptObject(SecondHomeWebActivity.this),"android"); 
	}
	
	public class JavaScriptObject {
		 Context mContext;

		public JavaScriptObject(Context mContext) {
			super();
			this.mContext = mContext;
		}
		@JavascriptInterface
		 public void loadHomePage() {
			Intent intent =new Intent(SecondHomeWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_HOME_TAG;
			startActivity(intent);
			finish();
			
		} 
		@JavascriptInterface
		 public void goToShoppingCart() {
			Intent intent =new Intent(SecondHomeWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_SHOPCART_TAG;
			startActivity(intent);
			finish();
			
		} 
		
		@JavascriptInterface
		public void appLoginFunc(){
			Intent intent =new Intent (SecondHomeWebActivity.this,LoginActivity.class);
			startActivity(intent);
		}
		@JavascriptInterface
		 public void appWeixinPay(String a) {
		
			sharedPreferences =getSharedPreferences("PAY", Context.MODE_PRIVATE);
			sharedPreferences.edit().clear();
			sharedPreferences.edit().putString("PAYINFO", a).commit();
			JSONObject json;
			try {
				json = new JSONObject(a);
				JSONObject payData = json.getJSONObject("data");
				Log.e("json",json.toString());
				
				if(json == null)
					return;
				
				
				PayReq req = new PayReq();
				
				req.appId =payData.getString("appId");
				Log.e("appId",req.appId);
				req.partnerId = payData.getString("partnerid");
				Log.e("partnerId",req.partnerId);
				req.prepayId=  payData.getString("prepayid");
				Log.e("prepayId",req.prepayId);
				req.packageValue = payData.getString("package_");
				Log.e("packageValue",req.packageValue);
				req.nonceStr=  payData.getString("noncestr");
				Log.e("nonceStr",req.nonceStr);
				req.timeStamp= payData.getString("timeStamp");
				Log.e("timeStamp",req.timeStamp);
				 req.sign= payData.getString("sign");
				 Log.e("sign",req.sign);
				
				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
	            signParams.add(new BasicNameValuePair("appid", req.appId));
				signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
				signParams.add(new BasicNameValuePair("package", req.packageValue));
				signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
				signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
				signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
				
				req.sign = genAppSign(signParams);
				
				api.sendReq(req);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			
			}		
		
		}
		
		// 二次签名
		private String genAppSign(List<NameValuePair> params) {
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < params.size(); i++) {
				sb.append(params.get(i).getName());
				sb.append('=');
				sb.append(params.get(i).getValue());
				sb.append('&');
			}
			sb.append("key=");
			sb.append(Constants.API_KEY);

			String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		
			return appSign;
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) &&  re_webView.canGoBack()) {
			 re_webView.goBack();
			 return true;
			}else{
				finish();
			}
			return super.onKeyDown(keyCode, event);
		}
}
